import java.io.*;
import java.net.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class DataServerThread extends Thread {

	private DataServer server;
	private Socket socket;
	
	public DataServerThread(DataServer serv, Socket sock) {
		this.server = serv;
		this.socket = sock;
		start();
	}
	
	//Server Logic ====================================
	private void processMsg(String msg) {
		String args = msg.substring(msg.indexOf(":")+1);
		
		if (msg.startsWith("LOGIN:")) {
			String username, password;
			username = args.substring(0, args.indexOf("|"));
			password = args.substring(args.indexOf("|")+1);
			login(username, password);
			return;
		}
		else if (msg.startsWith("CREATEUSER:")) {
			String username, password;
			username = args.substring(0, args.indexOf("|"));
			password = args.substring(args.indexOf("|")+1);
			Database.insert("INSERT INTO users (username, password) VALUES('" + username + "', '" + password + "')");
			login(username, password);
			return;
		}
		else if (msg.startsWith("CHECKUSER:")) {
			ResultSet results = Database.query("Select * FROM users WHERE username='" + args + "'");
			try { 
				while (results.next()) { 
					results.close();
					return; 
				} 
			} catch (SQLException e) {}
			server.sendToSocket("USERAVAILABLE:" + args, socket);
			return;
		}
		else if (msg.startsWith("JOINROOM:")) {
			Room old_room = server.rooms.get(socket);
			Room new_room = server.roomnames.get(args);
			old_room.delUser(socket);
			if (new_room == null)
				new_room = new Room(args, 6, server);
			new_room.addUser(socket);
		}
		else if (msg.startsWith("CHAT:")) {
			Room curr_room = server.rooms.get(socket);
			if (curr_room.name.equals("Lobby")) {
				server.sendToRoom("LOBBYCHAT:" + args, curr_room.name);
			} else {
				server.sendToRoom("CHAT:" + args, curr_room.name);
			}
		}
		else if (msg.startsWith("UPDATEUSERVAR:")) {
			String username, variable, value;
			username = server.usernames.get(socket);
			variable = args.substring(0, args.indexOf("|"));
			value    = args.substring(args.indexOf("|")+1);
			String cmd = "UPDATE users SET " + variable + "=" + value + " WHERE username='" + username + "'";
			Database.insert(cmd);
		}
		// Multiplayer commands
		else if (msg.startsWith("M") || msg.startsWith("S")) {
			Room game_room = server.rooms.get(socket);
			ArrayList<Socket> users = game_room.users;
			synchronized( users ) {
				// For each client ...
				for (int i=0;  i<users.size(); i++) {
					Socket other_user = users.get(i);
					if (!other_user.equals(socket))
						server.sendToSocket(msg, other_user);
				}
			}
		}
		else {
			//System.out.println("Msg not recognized: " + msg);
			server.sendToSocket(msg, socket);
		}
	}
		
	
	private void login(String username, String password) {
		ResultSet results = Database.query("Select * FROM users WHERE username='" + username + "' AND password='" + password + "'");
		try {
			while (results.next()) {
				// Get user data and send back
				String userdata = "LOGIN:";
				userdata += "username=" + results.getString("username");
				server.sendToSocket(userdata, socket);
				server.usernames.put(socket, username);
				server.lobby.addUser(socket);
				results.close();
				System.out.println(server.getTimeStamp() + username + " logged in.");
				return;
			}
		} catch (Exception e) { /* do nothing */ }
		
		String error = "LOGINFAILED:Username/password combination not found.";
		server.sendToSocket(error, socket);
	}

	
	public void run() {
		try {
			DataInputStream din = new DataInputStream( socket.getInputStream() );
	
			// Get new messages forever
			while (true) {
				String message = din.readUTF();
				//System.out.println(server.getTimeStamp() + "<< " + message);
				processMsg(message);
			}
		} 
		catch( EOFException ie ) { /* do nothing */ } 
		catch( IOException ie ) { /* do nothing */ } 
		finally {
			server.removeConnection( socket );
		}
	}
}
